import request from '@/utils/request';

// 统计API路径配置
export const API_STATISTICS = {
    ORDERS: '/api/statistics/orders',
    ORDERS_MONTHLY: '/api/statistics/orders/monthly',
    RECEIPTS: '/api/statistics/receipts',
    INVOICES: '/api/invoices/statistics/overall',
    INVOICES_CATEGORY: '/api/invoices/statistics/category',
    INVOICES_SUPPLIER: '/api/invoices/statistics/supplier',
    INVOICES_MONTHLY: '/api/invoices/statistics/trend/monthly',
};

/**
 * 获取订单统计数据
 * @param params 查询参数
 */
export function getOrderStatistics(params?: {
    startDate?: string;
    endDate?: string;
}) {
    return request({
        url: API_STATISTICS.ORDERS,
        method: 'get',
        params
    });
}

/**
 * 获取订单趋势数据（月度）
 * @param year 年份
 */
export function getOrderMonthlyTrend(year: number | Date) {
    // 确保将日期对象转换为年份整数
    let yearValue: number;
    if (year instanceof Date) {
        yearValue = year.getFullYear();
    } else if (typeof year === 'string') {
        // 处理ISO日期字符串
        yearValue = new Date(year).getFullYear();
    } else {
        yearValue = Number(year);
    }

    return request({
        url: API_STATISTICS.ORDERS_MONTHLY,
        method: 'get',
        params: {year: yearValue}
    });
}

/**
 * 获取收货单统计数据
 * @param params 查询参数
 */
export function getReceiptStatistics(params?: {
    year?: number | string;
}) {
    return request({
        url: API_STATISTICS.RECEIPTS,
        method: 'get',
        params
    });
}

/**
 * 获取发票趋势数据（月度）
 * @param year 年份
 */
export function getMonthlyTrend(year: number | string | Date) {
    // 确保将日期对象转换为年份整数
    let yearValue: number;
    if (year instanceof Date) {
        yearValue = year.getFullYear();
    } else if (typeof year === 'string') {
        // 处理ISO日期字符串或年份字符串
        try {
            // 尝试解析为数字
            yearValue = parseInt(year);
            if (isNaN(yearValue)) {
                // 如果不是纯数字，尝试解析为日期
                yearValue = new Date(year).getFullYear();
            }
        } catch (e) {
            console.error('年份字符串解析失败:', year, e);
            yearValue = new Date().getFullYear(); // 默认使用当前年份
        }
    } else {
        yearValue = Number(year);
    }

    // 构建请求参数
    const params = {year: yearValue};

    // 发送请求
    return request({
        url: API_STATISTICS.INVOICES_MONTHLY,
        method: 'get',
        params
    });
}

/**
 * 获取发票总体统计数据
 */
export function getOverallStatistics() {
    return request({
        url: API_STATISTICS.INVOICES,
        method: 'get'
    });
}

/**
 * 获取发票类别统计数据
 */
export function getStatisticsByCategory() {
    return request({
        url: API_STATISTICS.INVOICES_CATEGORY,
        method: 'get'
    });
}

/**
 * 获取发票供应商统计数据
 */
export function getStatisticsBySupplier() {
    return request({
        url: API_STATISTICS.INVOICES_SUPPLIER,
        method: 'get'
    });
} 